package com.hua.argi;

/**
 * @author: _hua
 * @created: 2019/3/28.
 * @updater:
 * @description:
 */
public class SingleLinkedList {

    private Node head;//头节点
    public int size;

    public SingleLinkedList(){
        size=0;
        head=null;
    }

    //链表的每个节点类
    private class Node{
        Object data;
        Node next;

        public Node(Object d){
            this.data=d;
        }
    }


    //在链表头添加元素
    public Object addHead(Object obj){
        Node newNode = new Node(obj);
        if(size==0){
            head=newNode;
        }else{
            newNode.next=head;//next存储原head
            head=newNode;//head存储新节点
        }
        size++;
        return obj;
    }

    //在链表头删除元素
    public Object deleteHead(){
        Object obj=head.data;
        head=head.next;
        size--;
        return obj;
    }

    //查找指定元素，找到了返回节点Node，找不到返回null
    public Node find(Object obj){
        Node current  = head;
        int tempSize =size;
        while (tempSize>0){
            if(obj.equals(current.data)){
                return current;
            }else{
                current=current.next;
                tempSize--;
            }
        }
        return  null;
    }


    //删除指定的元素，删除成功返回true
    public boolean delete(Object value){
        if(size!=0){
            Node current  =head;
            Node prenode =null;
            while (current!=null){
                if(!value.equals(current.data)){
                    prenode=current;
                    current=current.next;
                }else{
                    prenode.next=current.next;
                    current.data=null;
                    size--;
                    return  true;
                }
            }
        }

        return  false;
    }

    //判断链表是否为空
    public boolean isEmpty(){
       return (size == 0);
     }

    //显示节点信息
   public void display(){
        Node current  = head;
       System.out.print("[");
        while (current!=null){
            System.out.print(current.data);
            current=current.next;
        }
       System.out.print("]");
        System.out.println("");
   }

   public  static void main(String args[]){
       testSingleLinkedList();
   }

    public static void testSingleLinkedList(){
        SingleLinkedList singleList = new SingleLinkedList();
        singleList.addHead("A");
        singleList.addHead("B");
        singleList.addHead("C");
        singleList.addHead("D");
        //打印当前链表信息
        singleList.display();
        //删除C
        singleList.delete("C");
       // singleList.delete("B");
        singleList.display();
        //查找B
        System.out.println(singleList.find("B"));
    }

}
